import { loginPath, merchantLoginPath, merchantRoutePath } from '@/config';
import merchantManagerShopApi from '@/services/merchant-manager/shop';
import api from '@/services/user';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, useModel } from '@umijs/max';
import { Spin } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

const logout = async () => {
  const res = await api.logout();
  return res;
};
const merchantManagerShopApiLogout = async () => {
  const res = await merchantManagerShopApi.logout();
  return res;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { userInfo } = initialState || {};
  return <span className="anticon">{userInfo?.realname}</span>;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
  const actionClassName = useEmotionCss(({ token }) => {
    return {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });
  const { initialState, setInitialState } = useModel('@@initialState');
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    const { location } = history;
    const isMerchantRoute = location.pathname.includes(merchantRoutePath);
    const request = isMerchantRoute ? merchantManagerShopApiLogout : logout;
    const res = await request();
    if (res.success) {
      const urlParams = new URL(window.location.href).searchParams;
      /** 此方法会跳转到 redirect 参数所在的位置 */
      const redirect = urlParams.get('redirect');
      flushSync(() => {
        window.localStorage.removeItem('user_id');
        window.localStorage.removeItem('access_token');
        window.localStorage.removeItem('user_info');
        setInitialState((s) => ({ ...s, userInfo: undefined, authMenu: undefined } as any));
      });
      // Note: There may be security issues, please note
      if (![loginPath, merchantLoginPath].includes(window.location.pathname) && !redirect) {
        history.replace({
          pathname: isMerchantRoute ? merchantLoginPath : loginPath,
          // search: stringify({
          //   redirect: pathname + search,
          // }),
        });
      }
    }
  };
  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        loginOut();
        return;
      }
      history.push(`/account/${key}`);
    },
    [setInitialState],
  );

  const loading = (
    <span className={actionClassName}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { userInfo } = initialState;

  if (!userInfo || !userInfo.id) {
    return loading;
  }

  const menuItems = [
    ...(menu
      ? [
          {
            key: 'center',
            icon: <UserOutlined />,
            label: '个人中心',
          },
          {
            key: 'settings',
            icon: <SettingOutlined />,
            label: '个人设置',
          },
          {
            type: 'divider' as const,
          },
        ]
      : []),
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      {children}
    </HeaderDropdown>
  );
};
